package com.ye.common.security.service;

import com.ye.common.redis.service.RedisCache;
import com.ye.common.security.dto.SecurityUser;
import com.ye.common.security.utils.JwtUtil;
import com.ye.common.utils.StringUtils;
import com.ye.core.constant.Constants;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: baby
 * @Date: 2023/10/10 02:42
 * @Description:
 */
@Service
public class TokenService {
    private String header = "Authorization";
    @Autowired
    private RedisCache redisCache;

    public SecurityUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                //token不为空时, 解析token
                Claims claims = JwtUtil.parseJWT(token);
                //使用userid从Redis缓存中获取用户信息
                String redisKey = "login:" + claims.get("userId", Integer.class);
                SecurityUser loginUser = redisCache.getCacheObject(redisKey);
                return loginUser;
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }
}
